package com.windoent.yugioh;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.navigation.NavigationView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.windoent.yugioh.adapter.brvah.DrawaerRvAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.DrawaerLayoutListBean;
import com.windoent.yugioh.bean.UserBean;
import com.windoent.yugioh.bean.UserInfoBean;
import com.windoent.yugioh.bean.eventbus.BottomViewEvent;
import com.windoent.yugioh.bean.eventbus.MainEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.JumpHelper;
import com.windoent.yugioh.ui.activity.meinfo.AddressActivity;
import com.windoent.yugioh.ui.activity.meinfo.CaiPanGameManagerActivity;
import com.windoent.yugioh.ui.activity.meinfo.FeedBackActivity;
import com.windoent.yugioh.ui.activity.meinfo.GameManagerActivity;
import com.windoent.yugioh.ui.activity.meinfo.ModifyUserinfoActivity;
import com.windoent.yugioh.ui.activity.meinfo.MyGameRecordActivity;
import com.windoent.yugioh.ui.activity.meinfo.MyMsgActivity;
import com.windoent.yugioh.ui.activity.meinfo.RealNameAuthActivity;
import com.windoent.yugioh.ui.activity.meinfo.RealNameAuthSucessActivity;
import com.windoent.yugioh.ui.activity.registlogin.LoginActivity;
import com.windoent.yugioh.ui.activity.setting.SettingActivity;
import com.windoent.yugioh.ui.fragment.MeFragment;
import com.windoent.yugioh.ui.fragment.PointFragment;
import com.windoent.yugioh.ui.fragment.SaiShiFragment;
import com.windoent.yugioh.ui.fragment.ZiXunFragment;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.PermissionUtils;
import com.windoent.yugioh.utils.PickerStringUtils;
import com.windoent.yugioh.utils.SharedPreUtil;
import com.windoent.yugioh.utils.TDevice;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.HexagonImageView;
import com.windoent.yugioh.widget.dialog.DeleteSureDialog;
import com.windoent.yugioh.widget.dialog.LocationPermissionDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    //侧边栏
    private DrawerLayout mDrawerLayout;
    private NavigationView mNavView;
    private ImageView mIvAvatar;
    private ImageView mIvAvatarBorder;
    private LinearLayout mLlmodify;
    private TextView mTvModify;
    private ImageView mIvModify;
    private TextView mTvName;
    private TextView mTvSignature;
    private RecyclerView mRecyclerView;
    private LinearLayout mLlsetting;

    private FrameLayout mFragment;
    private LinearLayout mLlMessage;
    private ImageView mIvMessage;
    private TextView mTvMessage;
    private LinearLayout mLlEvent;
    private ImageView mIvEvent;
    private TextView mTvEvent;
    private LinearLayout mLlPoint;
    private ImageView mIvPoint;
    private TextView mTvPoint;
    private LinearLayout mLlMe;
    private ImageView mIvMe;
    private TextView mTvMe;
    private View mView;

    private ZiXunFragment messageFragment;//资讯
    private SaiShiFragment eventFragment;//赛事
    private PointFragment pointFragment;//积分
    private MeFragment meFragment;//我的
    private Fragment[] fragments;
    private int index = 0;
    private int currentIndex = 0;

    private DrawaerRvAdapter adapterSlide;
    private UserInfoBean.DataBean.UserBean user;
    private String avatarUrl = "";//头像url

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        super.initView();
        mView = (View) findViewById(R.id.view);
        immersiveStatusBar(mView);
        mFragment = (FrameLayout) findViewById(R.id.fragment);
        mLlMessage = (LinearLayout) findViewById(R.id.ll_message);
        mIvMessage = (ImageView) findViewById(R.id.iv_message);
        mTvMessage = (TextView) findViewById(R.id.tv_message);
        mLlEvent = (LinearLayout) findViewById(R.id.ll_event);
        mIvEvent = (ImageView) findViewById(R.id.iv_event);
        mTvEvent = (TextView) findViewById(R.id.tv_event);
        mLlPoint = (LinearLayout) findViewById(R.id.ll_point);
        mIvPoint = (ImageView) findViewById(R.id.iv_point);
        mTvPoint = (TextView) findViewById(R.id.tv_point);
        mLlMe = (LinearLayout) findViewById(R.id.ll_me);
        mIvMe = (ImageView) findViewById(R.id.iv_me);
        mTvMe = (TextView) findViewById(R.id.tv_me);

        getNavView();
    }

    private void getNavView() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mNavView = (NavigationView) findViewById(R.id.nav_view);
        mIvAvatar = (ImageView) findViewById(R.id.iv_avatar);
        mIvAvatarBorder = (ImageView) findViewById(R.id.iv_avatar_border);
        mLlmodify = (LinearLayout) findViewById(R.id.ll_modify);
        mTvModify = (TextView) findViewById(R.id.tv_modify);
        mIvModify = (ImageView) findViewById(R.id.iv_modify);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvSignature = (TextView) findViewById(R.id.tv_signature);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mLlsetting = mNavView.findViewById(R.id.ll_setting);
        // 禁止手势滑动
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        initAdapter(mRecyclerView);
        setSixAngle(avatarUrl, mIvAvatar);
        mLlmodify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user == null) {
                    defaultNothingUi(10314, "");
                    return;
                }
                //修改
                Intent intent = new Intent(mContext, ModifyUserinfoActivity.class);
                startActivity(intent);
            }
        });
        mLlsetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user != null) {
                    UserInfoBean.DataBean.UserBean.PlatformBean platform = user.getPlatform();
                    if (platform != null) {
                        Intent intent = new Intent(mContext, SettingActivity.class);
                        startActivity(intent);
                    }
                } else {
                    defaultNothingUi(10314, "");
                }
            }
        });
        mIvAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user == null) {
                    defaultNothingUi(10314, "");
                    return;
                }
                if (BaseMethod.notNull(avatarUrl)) {
                    JumpHelper.startPhotoViewNet(mContext, avatarUrl);
                }
            }
        });
    }

    private void setSixAngle(String url, ImageView imageView) {
        if (imageView != null)
            Glide.with(mContext).asBitmap().load(url).placeholder(R.drawable.drawable_default_avatar).error(R.drawable.drawable_default_avatar).listener(new RequestListener<Bitmap>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.drawable_default_avatar);
                    HexagonImageView hexagonImageView = new HexagonImageView(bitmap, imageView.getWidth(), imageView.getHeight());
                    imageView.setBackground(hexagonImageView);
                    return false;
                }

                @Override
                public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                    return false;
                }
            }).into(new CustomTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    Bitmap bitmap = resource == null ? BitmapFactory.decodeResource(getResources(), R.drawable.drawable_default_avatar) : resource;
                    HexagonImageView hexagonImageView = new HexagonImageView(bitmap, imageView.getWidth(), imageView.getHeight());
                    imageView.setBackground(hexagonImageView);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {
                }
            });

    }

    //侧边栏adapt
    private void initAdapter(RecyclerView mRecyclerView) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapterSlide = new DrawaerRvAdapter();
        mRecyclerView.setAdapter(adapterSlide);
        adapterSlide.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if (user == null) {
                    defaultNothingUi(10314, "");
                    return;
                }
                List<DrawaerLayoutListBean> data = adapterSlide.getData();
                DrawaerLayoutListBean bean = data.get(position);
                String name = bean.getName();
                if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_shiming))) {
                    //实名认证
                    if (user != null) {
                        boolean isReal = user.isIsReal();
                        if (isReal) {
                            Intent intent = new Intent(mContext, RealNameAuthSucessActivity.class);
                            intent.putExtra("realName", user.getRealName());
                            intent.putExtra("cardNumber", user.getCardNumber());
                            startActivity(intent);
                        } else {
                            startActivity(new Intent(mContext, RealNameAuthActivity.class));
                        }
                    }
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_shouhuo))) {
                    //收货地址
                    startActivity(new Intent(mContext, AddressActivity.class));
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_bisai))) {
                    //比赛管理
                    startActivity(new Intent(mContext, GameManagerActivity.class));
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_womsg))) {
                    //我的消息
                    startActivity(new Intent(mContext, MyMsgActivity.class));
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_bisairecord))) {
                    //比赛记录
                    startActivity(new Intent(mContext, MyGameRecordActivity.class));
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_caipanrecord))) {
                    //裁判记录
                    startActivity(new Intent(mContext, CaiPanGameManagerActivity.class));
                } else if (BaseMethod.notNull(name) && name.equals(getString(R.string.string_drawaerlayout_yijian))) {
                    //意见反馈
                    startActivity(new Intent(mContext, FeedBackActivity.class));
                }
            }
        });
    }

    //登录
    private void defaultNothingUi(int code, String msg) {
        if (code != 200) {//游客
            setDefaultSix(mIvAvatar);
            setText(mTvName, BaseMethod.notNullDefaultValueNull(getString(R.string.string_youke)));
            setText(mTvSignature, BaseMethod.notNullDefaultValueNull(getString(R.string.string_no_signature_data)));
        }
        if (code != 10314) {
            return;
        }
        DeleteSureDialog dialog = new DeleteSureDialog(mContext);
        dialog.setTvContent(BaseMethod.notNullDefaultValue(msg, getString(R.string.string_please_login_app)));
        dialog.setYesOnclickListener(new DeleteSureDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                SharedPreUtil.put(mContext, Constants.APPTOKEN, "");
                SharedPreUtil.put(mContext, Constants.USERID, 0);
                MyApplication.getInstance().cleanLoginInfo();
                MyApplication.getInstance().cleanMsgNumber();
                startActivity(new Intent(mContext, LoginActivity.class));
            }
        });
        dialog.show();
    }

    //默认头像
    private void setDefaultSix(ImageView imageView) {
        if (imageView != null) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.drawable_default_avatar);
            HexagonImageView hexagonImageView = new HexagonImageView(bitmap, imageView.getWidth(), imageView.getHeight());
            imageView.setBackground(hexagonImageView);
        }
    }

    //侧边栏数据
    private List<DrawaerLayoutListBean> getRvList() {
        List<DrawaerLayoutListBean> listBeans = new ArrayList<>();
        listBeans.clear();
        listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_one, getString(R.string.string_drawaerlayout_shiming)));
        listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_two, getString(R.string.string_drawaerlayout_shouhuo)));
        if (user != null && user.isIsCustomer())
            listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_three, getString(R.string.string_drawaerlayout_bisai)));
        listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_four, getString(R.string.string_drawaerlayout_womsg)));
        if (user != null && user.isIsPlayer())
            listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_five, getString(R.string.string_drawaerlayout_bisairecord)));
        if (user != null && user.isIsReferee())
            listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_six, getString(R.string.string_drawaerlayout_caipanrecord)));
        listBeans.add(new DrawaerLayoutListBean(R.drawable.drawable_chouti_seven, getString(R.string.string_drawaerlayout_yijian)));
        return listBeans;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (savedInstanceState != null) {
            messageFragment = (ZiXunFragment) getSupportFragmentManager().getFragment(savedInstanceState, ZiXunFragment.class.getSimpleName());
            eventFragment = (SaiShiFragment) getSupportFragmentManager().getFragment(savedInstanceState, SaiShiFragment.class.getSimpleName());
            pointFragment = (PointFragment) getSupportFragmentManager().getFragment(savedInstanceState, PointFragment.class.getSimpleName());
            meFragment = (MeFragment) getSupportFragmentManager().getFragment(savedInstanceState, MeFragment.class.getSimpleName());
        } else {
            messageFragment = ZiXunFragment.newsInstance();
            eventFragment = SaiShiFragment.newsInstance();
            pointFragment = PointFragment.newsInstance();
            meFragment = MeFragment.newsInstance();
        }
        fragments = new Fragment[]{messageFragment, eventFragment, pointFragment, meFragment};
        switchFragment(messageFragment);
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        boolean netLocation = PermissionUtils.checkPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION);
        boolean fineLocation = PermissionUtils.checkPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION);
        if (!netLocation || !fineLocation)
            initLocationPermissionDialog();
        else initLocationPermission();
        initDefaultSelect(true, false, false, false);
        // 获取测试设备ID
//        baiduId();
//        screenDensity();
    }

    //屏幕密度
    private void screenDensity() {
        float density = TDevice.getScreenDensity(mContext);
        float width = TDevice.getScreenWidth(mContext);
        float height = TDevice.getScreenHeight(mContext);
        ToastUtils.showText("密度：" + density + ",宽：" + width + ",高：" + height);
    }

    private void baiduId() {
        String testDeviceId = StatService.getTestDeviceId(mContext);
        Log.d("Main", "baiduId---->:" + testDeviceId);
    }


    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "首页界面");
        if (BaseMethod.notNull(getUserToken())) {
            getUserInfo();
        } else {
            if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                mDrawerLayout.closeDrawers();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "首页界面");
    }


    //保存下个人信息
    private void getUserInfo() {
        showLoadingDialog("");
        user = null;//置空
        PhoneLive.getUserInfoByToken(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                defaultNothingUi(10314, "");
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(response)) {
                            UserInfoBean bean = gson.fromJson(response, UserInfoBean.class);
                            if (bean != null) {
                                UserInfoBean.DataBean data = bean.getData();
                                if (data != null) {
                                    user = data.getUser();
                                    if (user != null) {
                                        //保存到Properties
                                        UserBean userBean = new UserBean();
                                        userBean.setReal(user.isIsReal());
                                        userBean.setPlayer(user.isIsPlayer());
                                        userBean.setReferee(user.isIsReferee());
                                        userBean.setCustomer(user.isIsCustomer());
                                        userBean.setSelectRole(user.getSelectRole());
                                        MyApplication.getInstance().saveMsgNumber(data.getMessageNums());
                                        String toJson = gson.toJson(userBean);
                                        MyApplication.getInstance().saveUserInfo(toJson);
                                        SharedPreUtil.put(mContext, Constants.USERID, user.getView_id());
                                        setTextUI(user);
                                        if (adapterSlide != null) {
                                            adapterSlide.setNewInstance(getRvList());
                                        }
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //设置数据
    private void setTextUI(UserInfoBean.DataBean.UserBean data) {
        avatarUrl = data.getAvatar();
        setSixAngle(avatarUrl, mIvAvatar);
        setText(mTvName, BaseMethod.notNullDefaultValue(data.getNickName(), getString(R.string.string_nickname_null)));
        setText(mTvSignature, BaseMethod.notNullDefaultValue(data.getSignature(), getString(R.string.string_no_signature_data)));
    }

    private void initLocationPermissionDialog() {
        LocationPermissionDialog dialog = new LocationPermissionDialog(mContext);
        dialog.setOnclickListener(new LocationPermissionDialog.onClickListener() {
            @Override
            public void onClick() {
                initLocationPermission();
            }

            @Override
            public void onCancelClick() {
                initPermission();
            }
        });
        dialog.show();
    }

    //高德定位权限
    private void initLocationPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        LogUtils.d("aBoolean:" + aBoolean);
                        if (aBoolean) {
                            initLocation();
                        } else {
                            ToastUtils.showText(getString(R.string.string_no_permission));
                        }
                    }
                });
    }

    //权限申请
    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                    }
                });
    }

    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;

    private void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置返回地址信息，默认为true
        mLocationOption.setNeedAddress(true);
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (mLocationOption != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        amapLocation.getLatitude();//获取纬度
                        amapLocation.getLongitude();//获取经度
                        amapLocation.getAccuracy();//获取精度信息
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(amapLocation.getTime());
                        df.format(date);//定位时间
                        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                        amapLocation.getCountry();//国家信息
                        amapLocation.getProvince();//省信息
                        amapLocation.getCity();//城市信息
                        amapLocation.getDistrict();//城区信息
                        amapLocation.getStreet();//街道信息
                        amapLocation.getStreetNum();//街道门牌号信息
                        amapLocation.getCityCode();//城市编码
                        amapLocation.getAdCode();//地区编码
                        amapLocation.getAoiName();//获取当前定位点的AOI信息
                        String location = PickerStringUtils.getLocation(amapLocation.getCity(), amapLocation.getDistrict());
                        LogUtils.d("------->getLocationType:" + amapLocation.getLocationType());
                        LogUtils.d("------->getAccuracy:" + amapLocation.getAccuracy());
                        LogUtils.d("------->getAddress:" + amapLocation.getAddress());
                        LogUtils.d("------->getCountry:" + amapLocation.getCountry());//国家信息
                        LogUtils.d("------->getProvince:" + amapLocation.getProvince());//省信息
                        LogUtils.d("------->getCity:" + amapLocation.getCity());//城市信息
                        LogUtils.d("------->getDistrict:" + amapLocation.getDistrict());//城区信息
                        LogUtils.d("------->getStreet:" + amapLocation.getStreet());//街道信息
                        LogUtils.d("------->getStreetNum:" + amapLocation.getStreetNum());//街道门牌号信息
                        LogUtils.d("------->getCityCode:" + amapLocation.getCityCode());//城市编码
                        LogUtils.d("------->getAdCode:" + amapLocation.getAdCode());//地区编码
                        LogUtils.d("------->getAoiName:" + amapLocation.getAoiName());
                        LogUtils.d("------->location:" + location);
                        SharedPreUtil.put(MainActivity.this, Constants.LOCATIONCURRENT, location);
                        SharedPreUtil.put(MainActivity.this, Constants.LOCATIONCURRENTCITYCODE, amapLocation.getAdCode());
                        if (BaseMethod.notNull(location) && mlocationClient != null)
                            mlocationClient.stopLocation();
                    } else {
                        //定位失败
                        SharedPreUtil.put(MainActivity.this, Constants.LOCATIONCURRENT, "");
                        SharedPreUtil.put(MainActivity.this, Constants.LOCATIONCURRENTCITYCODE, "");
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(false);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    public void initListener() {
        super.initListener();
        mLlMessage.setOnClickListener(this);
        mLlEvent.setOnClickListener(this);
        mLlPoint.setOnClickListener(this);
        mLlMe.setOnClickListener(this);
    }

    //切换Fragment
    Fragment mBeforeFragment = new Fragment();

    public void switchFragment(Fragment currentFragment) {
        if (currentFragment == null) {
            return;
        }
        if (currentFragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).show(currentFragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).add(R.id.fragment, currentFragment).commit();
        }
        mBeforeFragment = currentFragment;
    }

    private void initDefaultSelect(boolean message, boolean event, boolean point, boolean me) {
        mIvMessage.setSelected(message);
        mTvMessage.setSelected(message);
        mIvEvent.setSelected(event);
        mTvEvent.setSelected(event);
        mIvPoint.setSelected(point);
        mTvPoint.setSelected(point);
        mIvMe.setSelected(me);
        mTvMe.setSelected(me);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.ll_event:
                initDefaultSelect(false, true, false, false);
                index = 1;
                break;
            case R.id.ll_point:
                initDefaultSelect(false, false, true, false);
                index = 2;
                break;
            case R.id.ll_me:
                initDefaultSelect(false, false, false, true);
                index = 3;
                break;
            default:
                initDefaultSelect(true, false, false, false);
                index = 0;
                break;
        }
        if (currentIndex != index) {
            switchFragment(fragments[index]);
            currentIndex = index;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MainEvent event) {
        initDefaultSelect(false, true, false, false);
        index = 1;
        currentIndex = index;
        switchFragment(fragments[index]);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(BottomViewEvent event) {
        boolean open = event.isOpen();
        if (open) {
            if (user == null) {
                getUserInfo();
            }
            mDrawerLayout.openDrawer(Gravity.LEFT);
        } else {
            mDrawerLayout.closeDrawers();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (BaseMethod.notNull(getUserToken())) {
            getUserInfo();
        } else {
            if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                mDrawerLayout.closeDrawers();
            }
        }
        initDefaultSelect(true, false, false, false);
        index = 0;
        currentIndex = index;
        switchFragment(fragments[index]);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        //save fragments
        FragmentManager fm = getSupportFragmentManager();
        if (fragments != null) {
            for (Fragment f : fragments) {
                if (f != null && f.isAdded()) {
                    fm.putFragment(outState, f.getClass().getSimpleName(), f);
                }
            }
        }
        super.onSaveInstanceState(outState);

    }

    private long exitTime = 0;//记录时间

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.showText(getString(R.string.string_click_exit));
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册EventBus
        EventBus.getDefault().unregister(this);
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        OkHttpUtils.getInstance().cancelTag(this);
    }

}